package ru.sgu.codecenter.fidx.model;

import ru.sgu.codecenter.fidx.Configuration;
import ru.sgu.codecenter.fidx.OperationFailedException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class IndexInserter {
    public static final String FINALIZING_FILE_NAME = "SZDvE3jvyUG7LRHghceNYEpun6qPp6UBuESR6CvzPrMzt0IiwCDHxzm3dwKJ";
    private final BlockingQueue<File> queue;
    private final List<IndexInterterThread> threadList;

    public IndexInserter(Engine engine) {
        queue = new LinkedBlockingDeque<File>();
        threadList = new ArrayList<IndexInterterThread>();

        int threadCount = Configuration.getInserterThreadCount();
        for (int i = 0; i < threadCount; i++) {
            threadList.add(new IndexInterterThread(queue, engine));
        }
    }

    public void insert(File file) {
        try {
            queue.put(file);
        } catch (InterruptedException e) {
            throw new OperationFailedException("Unable to put [file=" + file + "] to queue.", e);
        }
    }

    public void stop() {
        try {
            queue.put(new File(FINALIZING_FILE_NAME));
            for (IndexInterterThread thread : threadList) {
                thread.join();
            }
        } catch (InterruptedException e) {
            throw new OperationFailedException("Unable to put finalizing file to queue.", e);
        }
    }
}
